import Vue from 'vue';
import {
	Message
} from 'element-ui'
import {
	Token
} from '../utils/storage';
import moment from 'moment'; //时间格式
import {
	parseTime
} from '../utils/utils';

String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, "");
}

export const toast = (message, type = 'error', duration = 1500) => {
	message = typeof(message) === 'string' ? message : JSON.stringify(message);
	Message({
		message,
		type,
		duration
	});
}
Vue.prototype.$toast = toast;

// 时间格式化
Vue.filter('formatTime', function(value, fmt) {
	return parseTime(value, fmt);
})
//表格合计
Vue.prototype.getTotal = (param, keys) => {
    const { columns, data } = param;
    if (!columns) return [];
    const sums = [];
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = "合计";
            return;
        }
        // if (index === 2) {
        //     sums[index] = data.length + "元";
        //     return;
        // }
        if (keys.includes(column.property)) {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return parseFloat((parseFloat(prev) + curr).toFixed(6));
                    } else {
                        return prev.toFixed(2);
                    }
                }, 0);
                sums[index];
            } else {
                sums[index] = "";
            }
        }
    });
    return sums;
};
// 提示弹窗
Vue.prototype.openMessage = function(content, type = "success") {
	this.$message({
		showClose: true,
		message: content,
		type: type,
		duration: 1500,
	});
};
//提示弹窗
Vue.prototype.openAlert = function(content, title, type = 'warning', callBack) {
	this.$alert(content.replace(/ERROR/, "系统提示"), title || "系统提示", {
		confirmButtonText: '确定',
		type: type,
		callback: _action => {
			if (callBack) callBack();
		}
	});
};
//确认弹窗
Vue.prototype.openConfirm = function(content, title = '系统提示', sureCallback, cancelCallback) {
	this.$confirm(content, title, {
		confirmButtonText: '是',
		cancelButtonText: '否',
		type: 'warning'
	}).then(() => {
		if (sureCallback) sureCallback();
	}).catch(() => {
		if (cancelCallback) cancelCallback();
	});
};
//日期封装
Date.prototype.format = function(fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
};

// 自定义上传
Vue.prototype.uploadExcel = function(param, queryConfig) {
	var that = this;
	var fileObj = param.file;
	var FileSize = fileObj.size / 1024 / 1024;
	if (FileSize > 10) {
		that.openAlert("文件不能大于10M", "提示", "error");
		return;
	}
	var fix = fileObj.name.split(".");
	if (fix[fix.length - 1] !== "xls" && fix[fix.length - 1] !== "xlsx") {
		that.openAlert("非法Excel 2003-2007文件", "提示", "error");
		return;
	}
	// for (var o in queryConfig) {
	//     FileController += "&" + o + "=" + queryConfig[o];
	// }

	var form = new FormData();
	form.append("FileData", fileObj); // 图片
	var instance = axios.create();
	instance
		.post(url, form, {
			headers: {
				"Content-Type": "multipart/form-data"
			},
			onUploadProgress: function(res) {
				//原生获取上传进度的事件
				let loaded = res.loaded,
					total = res.total;
				that.$nextTick(() => {
					that.ProgressNum = parseInt((loaded - 10) / total * 10000) / 100;
				});
			}
		})
		.then(data => {
			param.onSuccess(data.data);
		})
		.catch(e => {
			this.$refs.upload.clearFiles();
		});
}
Vue.prototype.uploadImg = function(param, qty = 0.3) {
	var fileObj = param.file;
	var FileSize = fileObj.size / 1024;
	// 小于100k就不压缩了
	if (FileSize < 100) {
		qty = 1;
	}
	//将base64转换为blob
	var dataURLtoBlob = function(dataurl) {
		var arr = dataurl.split(','),
			mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]),
			n = bstr.length,
			u8arr = new Uint8Array(n);
		while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}
		return new Blob([u8arr], {
			type: mime
		});
	}

	var dealImage = function(path, obj, callback) {
		var img = new Image();
		img.src = path;
		img.onload = function() {
			var that = this;
			// 默认按比例压缩
			var w = that.width,
				h = that.height,
				scale = w / h;
			w = obj.width || w;
			h = obj.height || (w / scale);
			var quality = obj.quality || 0.7; // 默认图片质量为0.7
			//生成canvas
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			// 创建属性节点
			var anw = document.createAttribute("width");
			anw.nodeValue = w;
			var anh = document.createAttribute("height");
			anh.nodeValue = h;
			canvas.setAttributeNode(anw);
			canvas.setAttributeNode(anh);
			ctx.drawImage(that, 0, 0, w, h);
			// 图像质量
			if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
				quality = obj.quality;
			}
			// quality值越小，所绘制出的图像越模糊
			var base64 = canvas.toDataURL('image/jpeg', quality);
			// 回调函数返回base64的值
			callback(base64);
		}
	}
	var reader = new FileReader(); //创建filereader对象
	reader.readAsDataURL(fileObj); //转换数据
	reader.onload = function(e) { //加载ok时触发的事件
		dealImage(this.result, {
			quality: qty,
		}, function(base) {
			//调用
			var blob = dataURLtoBlob(base);
			var newFile = new File([blob], fileObj.name, {
				type: fileObj.type
			});
			console.log(newFile)
			let r = new FileReader(); //本地预览
			r.onload = function() {
				// debugger;
				// $d.setAttribute("src", r.result); //给图片地址,显示缩略图
				// $uploading.show();
			}
			r.readAsDataURL(newFile); //Base64

			// var url = `http://memberapi.dev.gjd56sc.cn/api/Import/Upload`
			// for (var o in queryConfig) {
			//     FileController += "&" + o + "=" + queryConfig[o];
			// }

			var form = new FormData();
			form.append("FileData", fileObj); // 图片
			var instance = axios.create();
			instance
				.post(url, form, {
					headers: {
						"Content-Type": "multipart/form-data"
					},
					onUploadProgress: function(res) {
						//原生获取上传进度的事件
						// let loaded = res.loaded,
						//     total = res.total;
						// that.$nextTick(() => {
						//     that.ProgressNum = parseInt((loaded - 10) / total * 10000) / 100;
						// });
					}
				})
				.then(data => {
					param.onSuccess(data.data);
				})
				.catch(e => {
					return new Error(e);
				});
		});
	};

}
Vue.directive('dialogDrag', {
	bind(el, _binding, _vnode, _oldVnode) {
		const dialogHeaderEl = el.querySelector('.el-dialog__header');
		const dragDom = el.querySelector('.el-dialog');
		dialogHeaderEl.style.cursor = 'move';

		// 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
		const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null);

		dialogHeaderEl.onmousedown = (e) => {
			// 鼠标按下，计算当前元素距离可视区的距离
			const disX = e.clientX - dialogHeaderEl.offsetLeft;
			const disY = e.clientY - dialogHeaderEl.offsetTop;

			// 获取到的值带px 正则匹配替换
			let styL, styT;

			// 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
			if (sty.left.includes('%')) {
				styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100);
				styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100);
			} else {
				styL = +sty.left.replace(/\px/g, '');
				styT = +sty.top.replace(/\px/g, '');
			};

			document.onmousemove = function(e) {
				// 通过事件委托，计算移动的距离 
				const l = e.clientX - disX;
				const t = e.clientY - disY;

				// 移动当前元素  
				dragDom.style.left = `${l + styL}px`;
				dragDom.style.top = `${t + styT}px`;

				//将此时的位置传出去
				//binding.value({x:e.pageX,y:e.pageY})
			};

			document.onmouseup = function(_e) {
				document.onmousemove = null;
				document.onmouseup = null;
			};
		}
	}
})


// v-dialogDragWidth: 弹窗宽度拖大 拖小
Vue.directive('dialogDragWidth', {
	bind(el, binding, _vnode, _oldVnode) {
		const dragDom = binding.value.$el.querySelector('.el-dialog');

		el.onmousedown = (e) => {

			// 鼠标按下，计算当前元素距离可视区的距离
			const disX = e.clientX - el.offsetLeft;

			document.onmousemove = function(e) {
				e.preventDefault(); // 移动时禁用默认事件

				// 通过事件委托，计算移动的距离 
				const l = e.clientX - disX;
				dragDom.style.width = `${l}px`;
			};

			document.onmouseup = function(_e) {
				document.onmousemove = null;
				document.onmouseup = null;
			};
		}
	}
});

// 全局混入
Vue.mixin({
	data() {
		return {
			role_id: 0,
		}
	},
	created() {
		var moreParams = localStorage.getItem('moreParams');
		if (moreParams) {
			var p = JSON.parse(moreParams);
			localStorage.removeItem(moreParams);
			Object.keys(p).map(i => {
				this[i] = p[i];
			})
		}

		var t = Token.get();
		if (t && t.role_id) this.role_id = t.role_id;
	},
	methods: {
		goRoute(type, name, params, more) {
			if (more) {
				localStorage.setItem('moreParams', JSON.stringify(more));
			};
			switch (type) {
				case 'nt':
					this.$router.push({
						name,
						params,
						replace: true
					})
					break;
				case 'ntp':
					this.$router.push({
						path: name,
						query: params,
						replace: true
					})
					break;
				case 'nb':
					let view = this.$route;
					try {
						this.$store.dispatch("delView", view).then(({
							visitedViews
						}) => {
							const latestView = visitedViews.slice(-1)[0];
							if (latestView) {
								this.$router.push(latestView);
							} else {
								this.$router.push("/");
							}
						});
					} catch (error) {
						this.$router.go(-1);
					}
					break;
				default:
					break;
			}
		}
	}
})

Object.JXmonent = function(format, val) {
	if (val === null || val === "") {
		return "";
	}
	return moment(val).format(format);
};